package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author YWB
 * @Date 2021/1/15
 * desc 将返回信息封装为Response对象（根据输出流封装）
 **/
public class Response {
    private OutputStream outputStream;
    public Response(){

    }
    public Response(OutputStream outputStream){
        this.outputStream=outputStream;
    }

    /**
     * 使用输出流输出指定的字符串
     * @param content 输出的字符串
     * @throws IOException
     */
    public void outPut(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /**
     *根据url获取静态资源的绝对路径，然后将根据绝对路径读取静态资源文件，然后以流的形式输出
     * @param path url
     */
    public void outPutHtml(String path) throws IOException {
        //获取静态资源的绝对路径
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
        //输入静态资源文件
        File file = new File(absoluteResourcePath);
        if(file.exists()&&file.isFile()){
            //读取文件
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            //返回404
            HttpProtocolUtil.getHttpHeader404();
        }
    }

}
